// 保存当前所有标签页
function saveTabs() {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({ currentWindow: true }, tabs => {
      const tabData = tabs.map(tab => ({
        url: tab.url,
        title: tab.title,
      }));

      const now = new Date();
      const timestamp = now.toLocaleString();

      chrome.storage.local.get(["savedRecords"], result => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
          return;
        }

        let records = result.savedRecords || [];
        if (records.length >= 10) {
          records = records.slice(0, 9);
        }

        records.unshift({
          id: Date.now(),
          timestamp,
          tabs: tabData,
          tabCount: tabData.length,
        });

        chrome.storage.local.set({ savedRecords: records }, () => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
          } else {
            resolve(records);
          }
        });
      });
    });
  });
}
// 恢复指定URL列表
function restoreTabs(urls) {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({}, currentTabs => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }

      const currentUrls = currentTabs.map(tab => tab.url);
      const createPromises = [];

      for (const url of urls) {
        if (!currentUrls.includes(url)) {
          createPromises.push(
            new Promise(resolveCreate => {
              chrome.tabs.create({ url }, () => {
                if (chrome.runtime.lastError) {
                  console.error(
                    "创建标签页失败:",
                    chrome.runtime.lastError.message
                  );
                }
                resolveCreate();
              });
            })
          );
        }
      }

      Promise.all(createPromises)
        .then(() => resolve())
        .catch(error => reject(error));
    });
  });
}

// 删除指定记录
function deleteRecord(recordId) {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get(["savedRecords"], result => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }

      if (result.savedRecords) {
        const updatedRecords = result.savedRecords.filter(r => {
          //判断recordId是否是数组
          if (Array.isArray(recordId)) {
            return !recordId.includes(r.id);
          }
          return r.id !== recordId;
        });
        chrome.storage.local.set({ savedRecords: updatedRecords }, () => {
          if (chrome.runtime.lastError) {
            reject(new Error(chrome.runtime.lastError.message));
          } else {
            resolve(updatedRecords);
          }
        });
        console.log("delete", recordId, updatedRecords);
      } else {
        resolve([]);
      }
    });
  });
}

// 获取所有保存记录
function getSavedRecords() {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get(["savedRecords"], result => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
      } else {
        resolve(result.savedRecords || []);
      }
    });
  });
}

// 删除所有记录
function deleteAllRecords() {
  return new Promise((resolve, reject) => {
    chrome.storage.local.remove("savedRecords", () => {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
      } else {
        resolve([]);
      }
    });
  });
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  const handleCallback = (error, data) => {
    if (error) {
      sendResponse({ error: error.message });
    } else {
      sendResponse(data);
    }
  };

  try {
    switch (request.action) {
      case "save":
        saveTabs()
          .then(records => handleCallback(null, { records }))
          .catch(error => handleCallback(error));
        return true;
      case "restore":
        if (request.urls?.length > 0) {
          restoreTabs(request.urls)
            .then(() => handleCallback(null, { success: true }))
            .catch(error => handleCallback(error));
        } else {
          handleCallback(new Error("No URLs provided"));
        }
        return true;
      case "delete":
        deleteRecord(request.recordId)
          .then(records => handleCallback(null, { records }))
          .catch(error => handleCallback(error));
        return true;
      case "getRecords":
        getSavedRecords()
          .then(records => handleCallback(null, { records }))
          .catch(error => handleCallback(error));
        return true;
      case "deleteAll":
        deleteAllRecords()
          .then(records => handleCallback(null, { records }))
          .catch(error => handleCallback(error));
        return true;
      case "deleteSelected":
        deleteRecord(request.recordIds)
          .then(records => handleCallback(null, { records }))
          .catch(error => handleCallback(error));
        return true;
      default:
        handleCallback(new Error("Unknown action"));
        return false;
    }
  } catch (error) {
    handleCallback(error);
    return false;
  }
});
